--别忘了观战功能
local Sock = require"library.sock"
local bitser = require"library.bitser"

local network = class("Network") {
    Sock = nil;

    name = "",
    room = "",
    player_port = 0;
    signals = {};
}

function network:__init__(name)
    self.name = name or tostring(Game.RANDOM_NAME_TABLE);
    self.player_port = Game.PLAYER_PORT_A
end

function network:addSigbalConnect(signal_name,object,func)
    if self.signals[signal_name] == nil then
        self.signals[signal_name] = {}
    end
    table.insert(self.signals[signal_name],{
        object = object;
        func = func;
    })
end

function network:emitSignal(signal_name,...)
    if self.signals[signal_name] == nil then return end
    for index, item in ipairs(self.signals[signal_name]) do
        item.func(item.object,...)
    end
end

function network:connectServer(ip,port)
    self.Sock = Sock.newClient(ip,port);
    self.Sock:setSerialization(bitser.dumps,bitser.loads)
    self:initNetworkEvent()
    self.Sock:connect();
end

function network:initNetworkEvent()
    self.Sock:on("connect",function()
       --print("尝试连接到服务器")
        self:emitSignal("ServerConnect")
    end)

    self.Sock:on("disconnected",function()
        --print("尝试连接到服务器")
         self:emitSignal("ServerDisconnected")
    end)
    
    self.Sock:on("JoinServerSucceed",function ()
        self:emitSignal("JoinServerSucceed")
    end)

    self.Sock:on("PlayerJoin",function (pack)
        self:emitSignal("PlayerJoin")
        print(string.format("%s加入游戏",pack.name))
        local game_scene = Game.scene;
        local player_name = pack.name;
        game_scene.player2.label = player_name;
    end)

    self.Sock:on("JoinServerFail",function ()
        self:emitSignal("JoinServerFail")
        print("连接失败")
    end)

    self.Sock:on("CreateRoomSucceed",function()
        self:emitSignal("CreateRoomSucceed")
        print("创建房间成功")
    end)

    self.Sock:on("CreateRoomFail",function()
        self:emitSignal("CreateRoomFail")
        print("创建房间失败")
    end)

    self.Sock:on("GetRoomList",function(pack)
        self:emitSignal("GetRoomList",pack)
    end)

    self.Sock:on("JoinRoomSucceed",function (pack)
        self:emitSignal("JoinRoomSucceed",pack)
        print("成功加入房间")
    end)

    self.Sock:on("JoinRoomFail",function ()
        self:emitSignal("JoinRoomFail")
        print("加入房间失败")
    end)

    self.Sock:on("QuitRoom",function ()
        self:emitSignal("QuitRoom")
    end)

    self.Sock:on("KeyInput",function (pack)
        self:emitSignal("KeyInput")
    end)
end

function network:requestKeyInput(key)
    self.Sock:send("KeyInput",{
        room_name = self.room,
        player_port = self.player_port,
        key = key
    })
end

function network:requestCreateRoom(name)
    self.Sock:send("CreateRoom",{room_name = name,homeowners = self.name})
end

function network:requestJoinRoom(name)
    self.Sock:send("JoinRoom",{room_name = name,player_name = self.name})
end

return network;